<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring AI RAG演示</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .panel {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            flex: 1;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }
        h2 {
            color: #3498db;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-top: 0;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .chat-container {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 4px;
        }
        .user-message {
            background-color: #e1f5fe;
            align-self: flex-end;
            text-align: right;
        }
        .ai-message {
            background-color: #f1f1f1;
        }
        .file-upload {
            border: 2px dashed #3498db;
            padding: 20px;
            text-align: center;
            margin-bottom: 15px;
            border-radius: 4px;
            cursor: pointer;
        }
        .file-upload:hover {
            background-color: #e1f5fe;
        }
        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <h1>Spring AI RAG演示系统</h1>

    <div class="container">
        <div class="panel">
            <h2>文档上传</h2>
            <div class="file-upload" id="dropArea">
                <p>拖放文件到这里或点击选择文件</p>
                <input type="file" id="fileInput" style="display: none;" accept=".pdf,.md">
            </div>
            <div id="uploadStatus"></div>
            <button id="uploadBtn">上传文档</button>
        </div>

        <div class="panel">
            <h2>普通聊天</h2>
            <div class="chat-container" id="chatMessages"></div>
            <div class="form-group">
                <input type="text" id="chatInput" placeholder="输入您的问题...">
            </div>
            <button id="sendChatBtn">发送</button>
        </div>

        <div class="panel">
            <h2>RAG问答</h2>
            <div class="chat-container" id="ragMessages"></div>
            <div class="form-group">
                <input type="text" id="ragInput" placeholder="输入您的问题...">
            </div>
            <button id="sendRagBtn">发送</button>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 文件上传相关
            const dropArea = document.getElementById('dropArea');
            const fileInput = document.getElementById('fileInput');
            const uploadBtn = document.getElementById('uploadBtn');
            const uploadStatus = document.getElementById('uploadStatus');

            // 聊天相关
            const chatInput = document.getElementById('chatInput');
            const sendChatBtn = document.getElementById('sendChatBtn');
            const chatMessages = document.getElementById('chatMessages');

            // RAG相关
            const ragInput = document.getElementById('ragInput');
            const sendRagBtn = document.getElementById('sendRagBtn');
            const ragMessages = document.getElementById('ragMessages');

            // 文件拖放处理
            dropArea.addEventListener('click', () => fileInput.click());

            dropArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropArea.style.backgroundColor = '#e1f5fe';
            });

            dropArea.addEventListener('dragleave', () => {
                dropArea.style.backgroundColor = '';
            });

            dropArea.addEventListener('drop', (e) => {
                e.preventDefault();
                dropArea.style.backgroundColor = '';

                if (e.dataTransfer.files.length) {
                    fileInput.files = e.dataTransfer.files;
                    dropArea.querySelector('p').textContent = `已选择: ${fileInput.files[0].name}`;
                }
            });

            fileInput.addEventListener('change', () => {
                if (fileInput.files.length) {
                    dropArea.querySelector('p').textContent = `已选择: ${fileInput.files[0].name}`;
                }
            });

            // 文件上传
            uploadBtn.addEventListener('click', async () => {
                if (!fileInput.files.length) {
                    showStatus('请先选择文件', 'error');
                    return;
                }

                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append('file', file);

                try {
                    uploadBtn.disabled = true;
                    showStatus('正在上传文档...', '');

                    const response = await fetch('/api/documents/upload', {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const result = await response.text();
                        showStatus(result, 'success');
                        fileInput.value = '';
                        dropArea.querySelector('p').textContent = '拖放文件到这里或点击选择文件';
                    } else {
                        const error = await response.text();
                        showStatus(`上传失败: ${error}`, 'error');
                    }
                } catch (error) {
                    showStatus(`上传错误: ${error.message}`, 'error');
                } finally {
                    uploadBtn.disabled = false;
                }
            });

            // 普通聊天
            sendChatBtn.addEventListener('click', () => {
                const message = chatInput.value.trim();
                if (!message) return;

                addMessage(chatMessages, message, 'user-message');
                chatInput.value = '';

                // 调用聊天API
                fetchChatStream(`/chat/stream?input=${encodeURIComponent(message)}`, chatMessages);
            });

            // RAG问答
            sendRagBtn.addEventListener('click', () => {
                const question = ragInput.value.trim();
                if (!question) return;

                addMessage(ragMessages, question, 'user-message');
                ragInput.value = '';

                // 调用RAG API
                fetchChatStream(`/chat/rag?question=${encodeURIComponent(question)}`, ragMessages);
            });

            // 辅助函数
            function showStatus(message, type) {
                uploadStatus.textContent = message;
                uploadStatus.className = 'status ' + type;
            }

            function addMessage(container, text, className) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${className}`;
                messageDiv.textContent = text;
                container.appendChild(messageDiv);
                container.scrollTop = container.scrollHeight;
            }

            async function fetchChatStream(url, container) {
                try {
                    const response = await fetch(url);

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let aiMessage = '';

                    while (true) {
                        const { value, done } = await reader.read();

                        if (done) {
                            break;
                        }

                        const chunk = decoder.decode(value, { stream: true });
                        aiMessage += chunk;

                        // 更新AI消息
                        updateAIMessage(container, aiMessage);
                    }
                } catch (error) {
                    console.error('Error fetching chat stream:', error);
                    addMessage(container, `错误: ${error.message}`, 'error');
                }
            }

            function updateAIMessage(container, text) {
                // 查找现有的AI消息或创建新的
                let aiMessageDiv = container.querySelector('.ai-message:last-child');

                if (!aiMessageDiv || container.lastChild !== aiMessageDiv) {
                    aiMessageDiv = document.createElement('div');
                    aiMessageDiv.className = 'message ai-message';
                    container.appendChild(aiMessageDiv);
                }

                aiMessageDiv.textContent = text;
                container.scrollTop = container.scrollHeight;
            }
        });
    </script>
</body>
</html>
